/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.gp.patient.prescription;

import be.ugent.medirem.logic.GpRemote;
import be.ugent.medirem.logic.MedicationRemote;
import be.ugent.medirem.logic.PrescriptionRemote;
import be.ugent.medirem.persistence.entity.values.PrescriptionValues;
import be.ugent.medirem.persistence.exception.EntityNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Simon
 */
public class AddPatientPrescriptionServlet extends HttpServlet {

    @EJB
    private MedicationRemote medicationBean1;
    @EJB
    private MedicationRemote medicationBean;
    @EJB
    private PrescriptionRemote prescriptionBean;
    @EJB
    private GpRemote gpBean;

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Long pid = (Long) request.getSession().getAttribute("pid");

        Long mid = null;
        if (request.getParameter("mid") != null) {
            mid = Long.parseLong(request.getParameter("mid"));
            request.setAttribute("medicationId", mid);
        }
        if (mid == null) {
            mid = (Long) request.getAttribute("mid");
        }
        if (request.getParameter("mid") == null) {
            request.getRequestDispatcher("/gp/patient/prescription/medication").forward(request, response);
            return;
        }

        request.setAttribute("units", medicationBean.getAllUnits());
        try {
            request.setAttribute("medication", medicationBean.getMedicationDetails(mid));
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(AddPatientPrescriptionServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (EntityNotFoundException ex) {
            Logger.getLogger(AddPatientPrescriptionServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        request.setAttribute("patientid", pid);
        request.getRequestDispatcher("/gp/patient/prescription/add.jsp").forward(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean validate = true;
        Long pid = (Long) request.getSession().getAttribute("pid");
        request.setAttribute("patientid", pid);
        String username = request.getUserPrincipal().getName();
        Long gpId = gpBean.getGpId(username);

        PrescriptionValues p = (PrescriptionValues) request.getAttribute("prescription");
        p.setGpId(gpId);

        if (p.getMedicationId() == null) {
            request.setAttribute("flash", "An error occured when trying to make this prescription: no medication chosen");
            request.getRequestDispatcher("/gp/patient/prescription/new").forward(request, response);
            return;
        }
        if (p.getStartTime() == null || p.getEndTime() == null) {
            request.setAttribute("flash", "Fill in both start and end time");
            validate = false;
        } else {
            try {
                prescriptionBean.prescribeMedication(pid, p);
            } catch (Exception ex) {
                request.setAttribute("flash", "An error occured when trying to make this prescription");
                validate = false;
            }
        }

        if (validate) {
            response.sendRedirect(request.getContextPath() + "/gp/patient/prescriptions");
        } else {
            request.setAttribute("prescription", p);
            request.setAttribute("units", medicationBean.getAllUnits());
            try {
                request.setAttribute("medication", medicationBean.getMedicationDetails(p.getMedicationId()));
            } catch (Exception ex) {
                request.setAttribute("flash", "Invalid input received");
                request.getRequestDispatcher("/gp/patient/prescription/new").forward(request, response);
                return;
            }
            request.getRequestDispatcher("/gp/patient/prescription/add.jsp").forward(request, response);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
